<?php
/**
 * CONTENIDO extension pack (mpContenidoX), consists of multiple classes to
 * provide more features for Plugins/Modules.
 *
 * @package     mpContenidoX
 * @subpackage  VariableStorage
 * @author      Murat Purc <murat@purc.de>
 * @copyright   Copyright (c) 2008-2012 Murat Purc (http://www.purc.de)
 * @license     http://www.gnu.org/licenses/gpl-2.0.html - GNU General Public License, version 2
 * @version     $Id: ContainerDB.class.php 21 2012-07-16 21:33:14Z purcaholic $
 * @todo        Error handling
 */


defined('CON_FRAMEWORK') or die('Illegal call');


/**
 * Class mpVariableStorage_ContainerDB to store serialized configuration in a table.
 *
 * Needs a table, create it if not exists using following statement:
 * <code>
 * -- {prefix} ist almost con by default
 * CREATE TABLE {prefix}_variablestorage (
 *     `id` varchar(32) NOT NULL default '' COMMENT 'md5 hash as PK',
 *     `value` text COMMENT 'Serialized content of configuration',
 *     PRIMARY KEY (`id`)
 * )
 * </code>
 *
 * Usage:
 * <code>
 * // md5 hash of $options['key'] will be used as id in table {prefix}_variablestorage
 * $options['key'] = '/full/path/to/config.php';
 * $config = mpVariableStorage_Factory::get('dbstorage', $options);
 * </code>
 *
 * @todo  Add caching lifetime to table
 *
 * @package     mpContenidoX
 * @subpackage  VariableStorage
 * @author      Murat Purc <murat@purc.de>
 */
class mpVariableStorage_ContainerDB extends mpVariableStorage_Abstract implements mpVariableStorage_Interface
{

    /**
     * Database instance
     * @var  DB_Contenido
     */
    private $_oDB = null;

    /**
     * Name of table where the configuration is stored
     * @var  string
     */
    private $_table = '';


    /**
     * Constructor of mpVariableStorage_ContainerDB, delegates parameter to parent and sets some properties
     *
     * @param  array  $options  Assoziative options array as follows:
     * <code>
     * $options['key'] = Normally full path to configuration file, where the md5 hash will be calculated
     * </code>
     */
    public function __construct(array $options)
    {
        parent::__construct($options);
        $this->_key   = md5($this->_key);
        $this->_table = $GLOBALS['cfg']['sql']['sqlprefix'] . '_variablestorage';
        $this->_oDB   = new DB_Contenido();
    }


    /**
     * Checks, if configuration entry already exists.
     *
     * @return  bool
     */
    public function exists()
    {
        $sql = 'SELECT id FROM ' . $this->_table . ' WHERE id="' . $this->_key . '"';
        $this->_oDB->query($sql);
        return ($this->_oDB->next_record());
    }


    /**
     * Returns the configuration from db table
     *
     * @return  mixed  PHP variable or nul on error
     */
    public function get()
    {
        $sql = 'SELECT value FROM ' . $this->_table . ' WHERE id="' . $this->_key . '"';
        $this->_oDB->query($sql);
        if ($this->_oDB->next_record()) {
            return unserialize($this->_oDB->f('value'));
        } else {
            return null;
        }
    }


    /**
     * Serializes and writes passed configuration into the table.
     *
     * @return  bool  True on success otherwhise false
     */
    public function set($content)
    {
        $content = mysql_real_escape_string(serialize($content));
        if ($this->get()) {
            $sql = 'UPDATE ' . $this->_table . ' SET value="' . $content . '" WHERE id="' . $this->_key . '"';
        } else {
            $sql = 'INSERT INTO ' . $this->_table . ' (`id`, `value`) VALUES ("' . $this->_key . '", "' . $content . '")';
        }
        $result = $this->_oDB->query($sql);
        return ($result) ? true : false;
    }


    /**
     * Removes the configuration from table.
     *
     * @return  bool  True on success otherwhise false
     */
    public function remove()
    {
        $sql = 'DELETE FROM ' . $this->_table . ' WHERE id="' . $this->_key . '"';
        $result = $this->_oDB->query($sql);
        return ($result) ? true : false;
    }

}
